import os,sys,inspect,re
import cv2
import numpy as np

try:
    input_file = sys.argv[1]
except:
    input_file = 'crop.jpg'
try:
    output_file = sys.argv[2]
except:
    output_file = 'contour.jpg'


def restore_window(title):
    print(title)
    window_position_x,window_position_y = 1,1
    window_width,window_height = 640,480
    #cv2.namedWindow(title, cv2.WINDOW_NORMAL|cv2.WINDOW_KEEPRATIO)
    cv2.moveWindow(title,window_position_x,window_position_y)

def Sobel(origin):
#sobel非线性滤波采用梯度模的近似方式提取边缘,锐化图像,可以分别计算水平和垂直方向上的灰阶突变。
    sobelX = cv2.Sobel(origin,cv2.CV_64F,1,0)
    sobelY = cv2.Sobel(origin,cv2.CV_64F,0,1)
    resultX = numpy.uint8(numpy.absolute(sobelX))
    resultY = numpy.uint8(numpy.absolute(sobelY))
    result = cv2.bitwise_or(resultX,resultY)

    return result

def Contours(origin):
    ret,binary = cv2.threshold(image,127,255,cv2.THRESH_BINARY)
    contours,hierachy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    contours,hierachy = cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

    return contours

def draw_contours(img, cnts):  # conts = contours
    img = np.copy(img)
    img = cv2.drawContours(img, cnts, -1, (0, 255, 0), 2)
    return img

def refine_contours(contours):
    def flatten_list(source_list):
        dest_list = [y for x in source_list for y in x]
        return dest_list

    contourSize = np.array(contours).shape
    new_contours = []
    top,left,bottom,right = 70,40,230,190
    for index in range(contourSize[0]):
        for contour in contours[index]:
            cnt = flatten_list(contour)
            #print(cnt[0])
            if top < cnt[0] < bottom and left < cnt[1] < right:
                new_contours.append(cnt)
    return new_contours

def draw_contour_line(image,contours):
    def Line(image,x,y):
        new_img = cv2.line(image,x,y,(0,0,255),1,4)
    for cnt1 in contours:
        for cnt2 in contours:
            new_img = Line(image,tuple(cnt1),tuple(cnt2))

    return new_img

if __name__ == '__main__':
    image = cv2.imread(input_file)
    imgray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    ret,thresh = cv2.threshold(imgray,127,255,cv2.THRESH_BINARY)
    cv2.imwrite('imgray.jpg',imgray)
    cv2.imwrite('thresh.jpg',thresh)
    #mode = cv2.RETR_LIST
    mode = cv2.RETR_TREE
    method = cv2.CHAIN_APPROX_SIMPLE
    contours,hierachy = cv2.findContours(thresh,mode,method)
    contourSize = np.array(contours).shape
    #for index in range(np.array(contours).shape[0]):
        #print(contours[index])
    #print(contourSize)
    #cnt = contours[4]
    contour = cv2.drawContours(image,contours,-1,(0,255,0),3)
    new_contours = refine_contours(contours)
    print(new_contours)
    #print(new_contours.size)
    cv2.imwrite('contour.jpg',contour)
    new_contour = draw_contour_line(image,new_contours)
    cv2.imwrite('new_contour.jpg',new_contour)




    wait_key = cv2.waitKeyEx(1)
    cv2.imshow('image',image)
    restore_window('image')
    if wait_key == 27:
        cv2.destroyAllWindows()
        sys.exit()
    elif wait_key == 106: #j
        pass
    cv2.waitKey()

        


